import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'package:chat/common/service/HttpService.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class PhoneloginController extends GetxController {
  // 📌 常量配置
  static const int phoneLength = 11;
  static const int codeLength = 6;
  static const int countdownSeconds = 60;

  // 📌 控制器
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController imageCodeController = TextEditingController();
  final TextEditingController phoneCodeController = TextEditingController();

  // 图像验证码字节
  final Rx<Uint8List> code = Uint8List(0).obs;

  // 获取手机验证码按钮文本
  final RxString getPhoneCode = "获取手机验证码".obs;

  // 倒计时秒数
  final RxInt countdown = 0.obs;

  bool get isCounting => countdown.value > 0;

  Timer? _timer;

  @override
  void onReady() {
    super.onReady();
    _initData();
    // 监听倒计时，自动更新按钮文本
    ever(countdown, (_) => _updateButtonText());
  }

  @override
  void onClose() {
    _timer?.cancel();
    phoneController.dispose();
    imageCodeController.dispose();
    phoneCodeController.dispose();
    super.onClose();
  }

  // 初始化数据
  Future<void> _initData() async {
    await refreshImageCode();
  }

  // 刷新图像验证码
  Future<void> refreshImageCode() async {
    try {
      final response = await HttpService.to.get("/user/generateVerificationCode");
      final String base64Str = response.data["data"] ?? "";
      if (base64Str.isNotEmpty) {
        final String cleaned = base64Str.split(',').last;
        code.value = base64Decode(cleaned);
      }
    } catch (e) {
      EasyLoading.showError("刷新验证码失败");
      debugPrint("刷新验证码失败: $e");
    }
  }

  // 获取手机验证码
  Future<void> sendPhoneCode() async {
    final phone = phoneController.text.trim();
    final imageCode = imageCodeController.text.trim();

    if (!_validatePhone(phone) || !_validateCode(imageCode, "图形验证码")) return;

    try {
      final response = await HttpService.to.get("/user/sendVerificationCode", query: {"phoneNumber": phone, "imageCode": imageCode});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        startCountdown(countdownSeconds);
        EasyLoading.showSuccess("发送验证码成功");
      } else {
        EasyLoading.showError(response.data["msg"] ?? "发送验证码失败");
      }
    } catch (e) {
      EasyLoading.showError("发送手机验证码异常");
      debugPrint("发送手机验证码异常: $e");
    }
  }

  // 登录
  Future<void> phoneLoginSubmit() async {
    final phone = phoneController.text.trim();
    final phoneCode = phoneCodeController.text.trim();

    if (!_validatePhone(phone) || !_validateCode(phoneCode, "手机验证码")) return;

    try {
      final response = await HttpService.to.post("/user/phone/login", data: {"phoneNumber": phone, "phoneCode": phoneCode});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        // TODO: 存储 token
        EasyLoading.showSuccess("登录成功");
      } else {
        EasyLoading.showError(response.data["msg"] ?? "登录失败");
      }
    } catch (e) {
      EasyLoading.showError("手机号登录异常");
      debugPrint("手机号登录异常: $e");
    }
  }

  // 启动倒计时
  void startCountdown(int seconds) {
    _timer?.cancel();
    countdown.value = seconds;

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      countdown.value--;
      if (countdown.value <= 0) timer.cancel();
    });
  }

  // 更新按钮文本
  void _updateButtonText() {
    getPhoneCode.value = isCounting ? "${countdown.value}s后重发" : "获取手机验证码";
  }

  // 校验手机号
  bool _validatePhone(String phone) {
    if (phone.isEmpty || phone.length != phoneLength) {
      EasyLoading.showError("请输入正确的 $phoneLength 位手机号");
      return false;
    }
    return true;
  }

  // 校验验证码
  bool _validateCode(String code, String type) {
    if (code.isEmpty || code.length != codeLength) {
      EasyLoading.showError("$type不足 $codeLength 位");
      return false;
    }
    return true;
  }
}
